/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets.pages;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import ru.miit.elearning.hibernate.dao.CourseDAO;
import ru.miit.elearning.hibernate.dao.CurriculumDAO;
import ru.miit.elearning.hibernate.dao.HibernateUtil;
import ru.miit.elearning.hibernate.dto.CurriculumLevel;
import ru.miit.elearning.hibernate.dto.UserData;
import ru.miit.elearning.hibernate.dto.UserIdentity;
import ru.miit.elearning.hibernate.dto.WorkItem;
import ru.miit.elearning.hibernate.dto.beans.CourseBean;
import ru.miit.elearning.hibernate.dto.beans.StudentWithLabs;

/**
 *
 * @author Cyclone
 */
public class CurriculumTutorServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Session session = null;

        try {

//            int id = (Integer)request.getAttribute("id");
            int id = Integer.parseInt(request.getParameter("id"));

            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            CurriculumDAO curriculumDAO = new CurriculumDAO(session);
            int currentUserId = curriculumDAO.findUserIdByLogin(request.getRemoteUser());

            boolean isMyCurriculum = (currentUserId == id);

            List<CourseBean> courseBeanList = new ArrayList<CourseBean>();

            // Найти все курсы, на которые зачислен/назначен текущий или запрошенный пользователь
            List<UserData> userDataList = curriculumDAO.findCoursesByTutorId(id);
            //findCoursesByUserId(id);
            for (UserData userData : userDataList) {

                //WorkItem courseWorkItem = curriculumDAO.findWorkItemByUserData(userData.getId().getAccount(), userData.getId().getCurriculumLevel());
                WorkItem courseWorkItem = curriculumDAO.findWorkItem(userData.getId().getAccount(), userData.getId().getCurriculumLevel());

                CourseDAO courseDAO = new CourseDAO(session);
                List<StudentWithLabs> studentWithLabsList = new ArrayList<StudentWithLabs>();
                List<UserIdentity> studentList = courseDAO.findStudentsByCourse(userData.getId().getCurriculumLevel());
                for (UserIdentity student : studentList) {
                    StudentWithLabs studentWithLabs = new StudentWithLabs();
                    studentWithLabs.setUserIdentity(student);


                    List<WorkItem> labWorkItemList = new ArrayList<WorkItem>();

                    //List<CurriculumLevel> labList = curriculumDAO.findLabsByCourse(userData.getCurriculumLevel().getId());
                    List<CurriculumLevel> labList = userData.getCurriculumLevel().getLabList();

                    for (CurriculumLevel lab : labList) {
                        WorkItem labWorkItem = curriculumDAO.findWorkItem(student.getAccount(), lab.getId());

                        labWorkItemList.add(labWorkItem);
                    }
                    studentWithLabs.setWorkItemList(labWorkItemList);


                    studentWithLabsList.add(studentWithLabs);
                }

                /*
                List<WorkItem> labWorkItemList = new ArrayList<WorkItem>();

                Set<CurriculumLevel> labSet = userData.getCurriculumLevel().getCurriculumLevels();
                for (CurriculumLevel lab : labSet) {
                WorkItem labWorkItem = curriculumDAO.findWorkItem(userData.getId().getAccount(), lab.getId());

                labWorkItemList.add(labWorkItem);
                }
                 */

                CourseBean courseBean = new CourseBean();
                courseBean.setUserData(userData);
                courseBean.setWorkItem(courseWorkItem);
                //courseBean.setLabWorkItemList(labWorkItemList);
                courseBean.setStudentWithLabsList(studentWithLabsList);

                courseBeanList.add(courseBean);
            }


            //request.setAttribute("name", curriculumDAO.findUserNameById(id));
            if (!isMyCurriculum) {
                request.setAttribute("currentUserId", curriculumDAO.findUserIdByLogin(request.getRemoteUser()));
            }
            request.setAttribute("isMyCurriculum", isMyCurriculum);
            request.setAttribute("courseBeanList", courseBeanList);

            getServletContext().getRequestDispatcher("/curriculumTutor.jsp").forward(request, response);
            session.getTransaction().commit();

        } catch (Exception e) {
            Logger.getLogger(CurriculumTutorServlet.class.getName()).log(Level.SEVERE, null, e);
            if (session != null && session.isConnected()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null && session.isConnected()) {
                session.close();
            }
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
